import React, { useEffect, useRef } from 'react';
import { Spin } from 'antd';

interface Prop {
    isLoadingMore: boolean;
    loadMoreFn: () => void;
    propsId: string;
}
const LoadMore: React.FC<Prop> = (props) => {
    let timer: number | null = null
    const loadRef = useRef<HTMLDivElement>(null)
    const scrollBottomGetData = () => {
        // 当前加载更多文字距可视窗口顶部的位置
        const top = loadRef.current!.getBoundingClientRect().top
        // 窗口的高度
        const windowH = 700;
        // 如果小于窗口的高度，说明进入可视范围内了，也就是到底了
        if (top && top < windowH) {
            props.loadMoreFn()
        }
    }
    const onScroll = () => {
        if (props.isLoadingMore) {
            return
        }
        if (timer) {
            window.clearTimeout(timer)
        }
        timer = window.setTimeout(scrollBottomGetData, 500)
    }
    useEffect(() => {
        const propsIdDom = document.getElementById(props.propsId);
        propsIdDom.addEventListener('scroll', onScroll)
        return () => {
            propsIdDom.removeEventListener('scroll', onScroll)
        }
    }, [])
    return (
        <div className="load-more" ref={loadRef}>
            {
                props.isLoadingMore && <Spin spinning={true}>加载中...</Spin>
            }
        </div>
    )
}
export default LoadMore;